package com.kaifamiao.month05.day19;

import java.util.Scanner;

public class Test3 {

    /*
     *  已知运算符号：# $ 等价于 x # y = 2 * x + 3 * y + 4  x $ y = 3 * x + y + 2
     *  $ 优先级大于 # 根据输入 输出计算结果
     */
    public static void main(String[] args) {
        System.out.println("请输入表达式：");
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        str = str.replace(" ","");
        System.out.println("结果是：" + getResult(str) );
    }

    /**
     * 解析字符串
     */
    private static int getResult(String str) {
        if (str == null || str.length() == 0) {
           throw new NullPointerException("字符串输入不正确，不能为空！");
        }
        String s = "$";
        String j = "#";
        while (str.contains(s)) { // 先计算 $
            str = analyse(str, s);
        }
        while (str.contains(j)) { // 计算 #
            str = analyse(str, j);
        }
        return Integer.parseInt(str);
    }

    /**
     * 获取符号两边的数字，进行计算然后替换
     */
    private static String analyse(String str, String s) {
        int sIndex = str.indexOf(s);
        int l = 0, r = 0;
        for (int i = sIndex - 1; i >= 0; i--) {
            char c = str.charAt(i);
            if (!Character.isDigit(c)) {
                l = Integer.parseInt(str.substring(i + 1, sIndex));
                break;
            }
            if (i == 0) {
                l = Integer.parseInt(str.substring(0, sIndex));
            }
        }
        for (int i = sIndex + 1; i < str.length(); i++) {
            char c = str.charAt(i);
            if (!Character.isDigit(c)) {
                r = Integer.parseInt(str.substring(sIndex + 1, i));
                break;
            }
            if (i == str.length() - 1) {
                r = Integer.parseInt(str.substring(sIndex + 1));
            }
        }
        int result = Calculate(s,l,r);
        String old = l + "\\" + s + r;
        return str.replaceFirst(old, result + ""); // 把原来的式子替换成结果
    }

    /**
     * 计算 结果
     */
    private static int Calculate(String s, int x, int y) {
        if ("#".equals(s)) {
            return 2 * x + 3 * y + 4;
        } else if ("$".equals(s)) {
            return 3 * x + y + 2;
        }
        return 0;
    }
}
